# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/1/22
# @File   : IC17_Past2YearsLoanCardQuasiAccOvduMons.py
# @E-mail : zhaochen@bbdservice.com

'''eof
name:过去两年贷款和（准）贷记卡累计逾期月份数
code:IC17_Past2YearsLoanCardQuasiAccOvduMons
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import re
import datetime
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(table_Name):
    try:
        data = IC_DSJ['data'].get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}]
            if isinstance(data, list) and len(data) == 1 and data[0]['reportNo'] in null_type_list:
                return [{}]
            # 存在表 但为空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def Past2YearsLoanCardQuasiAccOvduMonsPre(*args):
    try:
        # 贷款明细表
        icrLoanInfo002LoanList = getTable(args[0])
        # 贷款5年逾期记录表
        icrLatest5YearOverdueDetailList = getTable(args[1])

        monthToday = datetime.datetime.now().year * 12 + datetime.datetime.now().month
        monthTwoYearsAgo = (datetime.datetime.now().year - 2) * 12 + datetime.datetime.now().month

        # 处理贷款逾期记录 贷款明细表
        loanOvduMonthList1 = []
        # 处理贷款逾期记录 5年逾期记录表
        loanOvduMonthList2 = []

        if icrLoanInfo002LoanList is None:
            loanOvduMonthList1 = None
        elif icrLoanInfo002LoanList == [{}]:
            loanOvduMonthList1 = []
        else:
            for i in icrLoanInfo002LoanList:
                latest24state = i.get('latest24State')
                endMonth = i.get('endMonth')
                account = i.get('account')
                if account not in null_type_list:
                    if latest24state not in null_type_list and endMonth not in null_type_list:

                        endMonthFact = float(endMonth[:4]) * 12 + float(endMonth[5:7]) if float(endMonth[5:7]) <= 12 else float(endMonth[5:6])

                        latest24stateSub = latest24state[::-1]
                        for i, state in enumerate(latest24stateSub):
                            if re.compile(r'\d').match(state):
                                if float(state) >=1 and float(state) <=7:
                                    if args[0] == 'ICRStdLoancardInfo002*Std':
                                        if float(state) > 2:
                                            for j in range(int(float(state)) - 2):
                                                loanOvduMonthList1.append(endMonthFact - i -j)
                                    else:
                                        for j in range(int(float(state))):
                                            loanOvduMonthList1.append(endMonthFact - i - j)
                                else:
                                    loanOvduMonthList1.append(None)
                                    continue

                            else:
                                pass

                    else:
                        pass
                else:
                    loanOvduMonthList1.append(None)
                    continue
            if len(set(loanOvduMonthList1)) == 1 and None in loanOvduMonthList1:
                loanOvduMonthList1 = None
            else:
                loanOvduMonthList1 = filter(lambda x:x!=None, loanOvduMonthList1)

        # 5年逾期记录表
        if icrLatest5YearOverdueDetailList is None:
            loanOvduMonthList2 = None
        elif icrLatest5YearOverdueDetailList == [{}]:
            loanOvduMonthList2 = []
        else:
            for i in icrLatest5YearOverdueDetailList:
                month = i.get('month')
                lastmonth = i.get('lastMonths')
                account = i.get('account')
                if account not in null_type_list:
                    if month not in null_type_list and lastmonth not in null_type_list \
                            and isfloat(lastmonth):
                        monthFact = float(month[:4]) * 12 + float(month[5:7]) if float(month[5:7])<=12 else float(month[5:6])
                        if float(lastmonth) >=1 and float(lastmonth) <= 7:
                            if monthFact > monthTwoYearsAgo and monthFact <= monthToday:
                                if args[1] == 'ICRLatest5YearOverdueDetail*Std':
                                    if float(lastmonth) > 2:
                                        for j in range(int(float(lastmonth)-2)):
                                            loanOvduMonthList2.append(monthFact - j)
                                else:
                                    for j in range(int(float(lastmonth))):
                                        loanOvduMonthList2.append(monthFact - j)
                            else:
                                pass
                        else:
                            loanOvduMonthList2.append(None)
                    else:
                        loanOvduMonthList2.append(None)
                else:
                    loanOvduMonthList2.append(None)
            if len(set(loanOvduMonthList2)) == 1 and None in loanOvduMonthList2:
                loanOvduMonthList2 = None
            else:
                loanOvduMonthList2 = filter(lambda x:x!=None, loanOvduMonthList2)

        if loanOvduMonthList1 is None and loanOvduMonthList2 is None:
            return None
        else:
            loanOvduMonthList1 = loanOvduMonthList1 if loanOvduMonthList1 != None else []
            loanOvduMonthList2 = loanOvduMonthList2 if loanOvduMonthList2 != None else []
            return loanOvduMonthList1 + loanOvduMonthList2
    except:
        return None

def IC17_Past2YearsLoanCardQuasiAccOvduMons():
    try:
        # 贷款信息
        dk = Past2YearsLoanCardQuasiAccOvduMonsPre(*('ICRLoanInfo002*Loan', 'ICRLatest5YearOverdueDetail*Loan'))
        # 贷记卡信息
        djk = Past2YearsLoanCardQuasiAccOvduMonsPre(*('ICRLoancardInfo002*Card', 'ICRLatest5YearOverdueDetail*Card'))
        # 准贷记卡信息
        zdjk = Past2YearsLoanCardQuasiAccOvduMonsPre(*('ICRStdLoancardInfo002*Std', 'ICRLatest5YearOverdueDetail*Std'))

        if dk is None and djk is None and zdjk is None:
            return u'缺失值'
        else:
            dk = dk if dk != None else []
            djk = djk if djk != None else []
            zdjk = zdjk if zdjk != None else []
            return len(set(dk + djk + zdjk))
    except:
        return u'缺失值'

result = IC17_Past2YearsLoanCardQuasiAccOvduMons()
